// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

const WEEK_OFFSET = 7 * 24 * 60 * 60 * 1000;

// 云函数入口函数
exports.main = async (event) => {
  const wxContext = cloud.getWXContext();
  const openid = event.openid || wxContext.OPENID;
  const db = cloud.database();
  const dateSkip = event.dateSkip || Date.now();
  const duration = event.duration || WEEK_OFFSET;
  const limit = event.limit || 20;

  const result = await db.collection('histories').aggregate().match({
    time: db.command.lt(dateSkip).gt(dateSkip - duration),
    openid: openid
  }).lookup({
    from: 'books',
    localField: 'book',
    foreignField: '_id',
    as: 'book'
  }).sort({ time: -1 }).limit(limit).end();

  result['data'] = result.list;

  return {
    result: result
  };
}
